package cn._2dland.bots.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.bots.TaskManager;
import cn._2dland.bots.jdo.AccountManager;
import cn._2dland.bots.jdo.models.Account;

@SuppressWarnings("serial")
public class ManagerServlet extends HttpServlet {
	public static final int ACTION_CREATE = 1;
	public static final int ACTION_MODIFY = 2;
	public static final int ACTION_DELETE = 3;

	public void init() throws ServletException {
		super.init();
		//TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String actionStr = req.getParameter("action");
		String acctIdStr = req.getParameter("acctid");
		String result = null;
		AccountManager am = new AccountManager();
		try{
			int action = Integer.parseInt(actionStr);
			long acctID = acctIdStr==null ? 0 : Long.parseLong(acctIdStr);
			switch(action) {
			case ACTION_CREATE:
				// 创建帐号
				acctID = AccountManager.create(req.getParameter("username"), req.getParameter("password"));
				// 为帐号创建任务队列
				TaskManager.createTask(acctID, BotServlet.ACTION_PICK);
				TaskManager.createTask(acctID, BotServlet.ACTION_RENEW);
				break;
			case ACTION_MODIFY:
				// 修改帐号
				am.begin();
				Account acct = am.getAccount(acctID);
				acct.setPassword(req.getParameter("password"));
				acct.setStatus(Integer.parseInt(req.getParameter("status")));
				am.commit();
				break;
			case ACTION_DELETE:
				// 删除帐号
				am.begin();
				am.removeAccount(acctID);
				am.commit();
			}
			result = "{\"ok\":1, \"aid\":" + acctID + "}";
		}
		catch (Exception e) {
			result = "{\"ok\":0}";
			e.printStackTrace();
		}
		finally {
			am.close();
		}
		resp.setContentLength(result.length());
		resp.getWriter().print(result);
	}
}